/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cestum.cave.ui.components.wave
{
import flash.events.Event;

import mx.controls.List;
import mx.core.ClassFactory;
import mx.events.ItemClickEvent;
import mx.events.ListEvent;

import org.cestum.cave.ui.components.InboxItemRenderer;
import org.cestum.cave.ui.events.WaveSelectedEvent;
import org.goverla.collections.HashMap;
import org.waveprotocol.wave.model.document.operation.BufferedDocOp;
import org.waveprotocol.wave.model.wave.data.WaveletData;

[Event(name="waveSelected", type="org.cestum.cave.ui.events.WaveSelectedEvent")]
[ManagedEvents("waveSelected")]
public class WaveList extends List
	
{
	private var waveListItemFactory:ClassFactory;
	[Embed(source="images/male_user.png")]
	public var userIco:Class;
	[Embed(source="images/unread_16.png")]
	public var readUnread:Class;

	public var read:Boolean = false;
	public function WaveList()
	{
		super();
//		super.itemRenderer = new WaveItemRenderer();
		waveListItemFactory = new ClassFactory(InboxItemRenderer);
		waveListItemFactory.properties = {removeItemFunction:deleteWave,
			iconImage:userIco,
			readUnreadImage:readUnread,
			readUnreadFunc:toggleReadUnread,
			labelFunction:inboxItemText,
			labelStyle:"waves",
			labelTitle:"Wave: "};
		super.itemRenderer = waveListItemFactory;
		this.addEventListener(ItemClickEvent.ITEM_CLICK, waveSelected);
		addEventListener(Event.ADDED_TO_STAGE, addToStage);
	}
	
	public function addToStage(event:Event):void {
		dispatchEvent(new Event('configureIOC', true));
	}
	
	function waveSelected(event:ListEvent):void {
		dispatchEvent(new WaveSelectedEvent("waveSelected"));
	}
	
	private function inboxItemText(data:WaveletData):String {
		if (data == null)
			return null;
		var docs:HashMap = data.getDocuments();
		if ( docs != null && docs.values.length > 0) {
			var split:String = BufferedDocOp(docs.values[0]).toString();
			return data.getWaveletName().waveletId.getId() + " - " + 
				split.slice(0,10).concat("...");
		} else {
			return data.getWaveletName().waveletId.getId() + " ...";
		}
//		this.percentWidth
	}

	private function deleteWave():void {
//		if (parentDocument instanceof SwatUIConsole) {
//			SwatUIConsole(parentDocument).presenter.removeWave();
//		}
	}
	
	private function toggleReadUnread():Boolean {
		return this.read;
	}
}
}